package com.dylovedz.javafxphone.service;

import com.dylovedz.javafxphone.domain.WechatApp;
import com.dylovedz.javafxphone.repository.WechatAppRepository;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class WechatAppService {

    @Resource
    private WechatAppRepository wechatAppRepository;

    public WechatApp findById(Integer id) {
        return wechatAppRepository.findById(id).orElse(new WechatApp());
    }

    public WechatApp findByAppId(String appId) {
        return wechatAppRepository.findByAppId(appId).orElse(new WechatApp());
    }

    public List<WechatApp> findAll() {
        return wechatAppRepository.findAll(Sort.by(Sort.Direction.DESC, "id"));
    }

    public WechatApp save(String appId, String appSecret) {
        WechatApp wechatApp = findByAppId(appId);
        if (wechatApp.getAppId() == null) {
            wechatApp = new WechatApp();
            wechatApp.setAppId(appId);
            wechatApp.setAppSecret(appSecret);
            wechatAppRepository.save(wechatApp);
        }
        return wechatApp;
    }
}
